// miniprogram/pages/book_details/book_details.js
const db = require('../../utils/db');
const strutil = require('../../utils/str');

let id;
let mode;

Page({
  data: {
    busy: {
      type: Boolean,
      value: true
    },
    book: {
      type: Object,
      value: {}
    },
    allowBorrow: {
      type: Boolean,
      value: false
    },
    isFavorite: {
      type: Boolean,
      value: false
    },
    found: {
      type: Boolean,
      value: false
    }
  },

  onLoad: function (options) {
    mode = options.mode || 'id';
    id = options.input;
  },

  onReady: function () {
    this.setData({
      busy: true,
      found: false,
      allowBorrow: false,
      allowReturn: false,
      isFavorite: false
    });
    const fn = mode === 'id' ? db.getBook.bind(db) : db.getBookByIsbn.bind(db);
    fn(id).then(res => {
      const out = res.data;
      if (out.length < 1) {
        this.setData({
          busy: false,
          found: false
        });
      } else {
        const book = res.data[0];
        const allowBorrow = book.location.reduce((last, now) => now.present || last, false);
        book.location.map(it => it['friendlyLocation'] = strutil.toFriendlyLocation(it.location));
        db.isFavorite(book._id).then(res => {
          this.setData({
            isFavorite: res
          });
        });
        this.setData({
          busy: false,
          found: true,
          book: book,
          allowBorrow: allowBorrow
        });
        console.log(book);
        db.addHistory(book._id);
      }
    });
  },

  onShow: function () {

  },

  onHide: function () {

  },

  onUnload: function () {

  },

  onShareAppMessage: function () {
    // ?
  },

  onCoverTap: function () {
    wx.previewImage({
      urls: [ this.data.book.cover ],
    });
  },

  onFavoriteTap: function () {
    if (this.data.isFavorite) {
      this.setData({
        isFavorite: false
      });
      db.removeFavorite(this.data.book._id).then(() => {
        wx.showToast({
          title: '取消收藏',
        });
      });
    } else {
      this.setData({
        isFavorite: true
      });
      db.addFavorite(this.data.book._id).then(() => {
        wx.showToast({
          title: '收藏成功',
        });
      });
    }
  },

  onBorrowTap: function () {
    wx.navigateTo({
      url: '../proxy_borrow/proxy_borrow?id=' + this.data.book._id,
    });
  }
})